<script setup>
import { computed, getCurrentInstance, onBeforeUnmount, onUnmounted, ref, watch } from "vue";
import { CreateOrder } from "@/api/order.js"
import { closeToast, showDialog, showFailToast, showLoadingToast, Loading } from "vant";
import useStore from "@/store/index.js";
import socket from "@/utils/socket.js";

const { websocket } = socket("ws://127.0.0.1:8081/ws/1")

const { userInfo } = useStore()
const { proxy } = getCurrentInstance()

const defaultAddress = computed(() => userInfo.getDefaultAddress)


const list = ref(JSON.parse(localStorage.getItem("goods_detail_submit")) || []);
const addressList = computed(() => userInfo.getAddress || [])
const show = ref(false)

const chosenAddressId = ref(defaultAddress.value?.id || 0);
const dialogVisible = ref(false)
const orderInfo = ref({
	sn: undefined,
	state: 0
})

const coupon = {
	available: 1,
	condition: '无门槛\n最多优惠150元',
	reason: '',
	value: 15000,
	name: '长得帅优惠卷',
	startAt: 1489104000,
	endAt: 1514592000,
	valueDesc: '150',
	unitDesc: '元',
};

const coupons = ref([coupon]);
const showList = ref(false);
const chosenCoupon = ref(-1);
const payVisible = ref(false)

const onChange = (index) => {
	showList.value = false;
	chosenCoupon.value = index;
};
const onExchange = (code) => {
	coupons.value.push(coupon);
};


const totalPrice = ref(0);
const totalNum = ref(0)
const payType = ref(1)

watch(() => list.value, (val) => {
	totalPrice.value = list.value.reduce((pre, item) => pre + item.goodsNum * item.goodsPrice, 0)
	totalNum.value = list.value.reduce((pre, item) => pre + item.goodsNum, 0)
	totalPrice.value *= 100
}, {
	deep: true,
	immediate: true
})


// 提交订单事件
const onSubmit = async () => {
	try {
		const res = await CreateOrder({
			goodsDetail: list.value,
			address: defaultAddress.value
		})
		orderInfo.value.sn = res.data.sn
		orderInfo.value.state = res.data.state
		localStorage.removeItem("goods_detail_submit")
		window.open(res.data.url, "_blank")
		payVisible.value = false
		dialogVisible.value = true
	} catch (e) {
	}
}

//连接发生错误的回调方法
websocket.onerror = function () {
	console.log("error");
};

//连接成功建立的回调方法
websocket.onopen = function () {
	console.log("连接成功");
}

//接收到消息的回调方法
websocket.onmessage = function (event) {
	const info = JSON.parse(event.data);
	orderInfo.value.state = info.state
	orderInfo.value.sn = info.sn
}

// 销毁关闭socket
onUnmounted(() => {
	// 退出销毁websocket
	websocket.close();
})

const onClickLeft = () => proxy.$router.back()

onBeforeUnmount(() => {
	localStorage.removeItem("goods_detail_submit")
})

const addAddress = () => proxy.$router.push("/addAddress")

const showPopup = () => {
	show.value = true
}

const onAdd = () => {
	proxy.$router.push("/addressList")
}

// 改变选中地址
const changeAddress = (row, index) => {
	userInfo.updateAddressIndex(index)
	show.value = false
}

const payConfirm = () => {
	if (orderInfo.value.state == 2) {
		onClickLeft()
	} else {
		proxy.$router.push('/mine')
	}
}


</script>

<template>
	<van-nav-bar title="提交订单" left-arrow @click-left="onClickLeft" />
	<div class="content">
		<div class="bg-[#fff] px-[20px] py-[10px]">
			<van-tag type="primary" class="mr-[10px]">商城配送</van-tag>
			<span class="text-[#ccc]">由平台为您提供配送服务</span>
		</div>
		<van-contact-card type="add" add-text="添加地址" @click="addAddress" v-if="!defaultAddress?.id" />
		<div v-else class="bg-[#fff] px-[20px] py-[10px] flex justify-between items-center">
			<div>
				<div class="flex text-[16px]">
					<div class="mr-[10px]">{{ defaultAddress.name }}</div>
					<div>{{ defaultAddress.tel }}</div>
				</div>
				<div class="flex text-[14px]">
					<div class="text-[red] mr-[10px]" v-if="defaultAddress.isDefault">[默认]</div>
					<div class="text-[#7b7b7b]">{{ defaultAddress.address }}</div>
				</div>
			</div>
			<van-icon @click="showPopup" name="edit" size="20" />
		</div>
		<div class="text-[18px] px-[20px] py-[5px] bg-[#fff] mt-[10px]">共{{ totalNum }}件商品</div>
		<van-card :price="item.goodsPrice.toFixed(2)" :desc="item.goodsNorm" :title="item.title" :thumb="item.banner"
			v-for="item in list" :key="item.id" :num="item.goodsNum">
		</van-card>
		<!-- 优惠券单元格 -->
		<van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
		<!-- 优惠券列表 -->
		<van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;" class="mt-[10px]">
			<van-coupon-list :coupons="coupons" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons"
				@change="onChange" @exchange="onExchange" />
		</van-popup>
	</div>
	<van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit">
		<template #tip>
			你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
		</template>
	</van-submit-bar>
	<van-popup v-model:show="show" position="bottom" :style="{ height: '50%', overflow: 'auto' }">
		<div class="flex">
			<h2 class="text-[18px] text-center py-[15px] flex-1">选择地址</h2>
			<div class="flex items-center px-[5px]" @click="show = false"><van-icon name="cross" size="25" /></div>
		</div>
		<van-address-list v-model="chosenAddressId" :list="addressList" default-tag-text="默认" @add="onAdd"
			add-button-text="选择其他地址" right-icon="" @select="changeAddress" />
	</van-popup>
	=======
	<van-nav-bar title="提交订单" left-arrow @click-left="onClickLeft" />
	<div class="content">
		<div class="bg-[#fff] px-[20px] py-[10px]">
			<van-tag type="primary" class="mr-[10px]">商城配送</van-tag>
			<span class="text-[#ccc]">由平台为您提供配送服务</span>
		</div>
		<van-contact-card type="add" add-text="添加地址" @click="addAddress" v-if="!defaultAddress?.id" />
		<div v-else class="bg-[#fff] px-[20px] py-[10px] flex justify-between items-center">
			<div>
				<div class="flex text-[16px]">
					<div class="mr-[10px]">{{ defaultAddress.name }}</div>
					<div>{{ defaultAddress.tel }}</div>
				</div>
				<div class="flex text-[14px]">
					<div class="text-[red] mr-[10px]" v-if="defaultAddress.isDefault">[默认]</div>
					<div class="text-[#7b7b7b]">{{ defaultAddress.address }}</div>
				</div>
			</div>
			<van-icon @click="showPopup" name="edit" size="20" />
		</div>
		<div class="text-[18px] px-[20px] py-[5px] bg-[#fff] mt-[10px]">共{{ totalNum }}件商品</div>
		<van-card :price="item.goodsPrice.toFixed(2)" :desc="item.goodsNorm" :title="item.title" :thumb="item.banner"
			v-for="item in list" :key="item.id" :num="item.goodsNum">
		</van-card>
		<!-- 优惠券单元格 -->
		<van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
		<!-- 优惠券列表 -->
		<van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;" class="mt-[10px]">
			<van-coupon-list :coupons="coupons" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons"
				@change="onChange" @exchange="onExchange" />
		</van-popup>
	</div>
	<van-submit-bar :price="totalPrice" button-text="提交订单" @submit="payVisible = true">
	</van-submit-bar>
	<van-popup v-model:show="show" position="bottom" :style="{ height: '50%', overflow: 'auto' }">
		<div class="flex">
			<h2 class="text-[18px] text-center py-[15px] flex-1">选择地址</h2>
			<div class="flex items-center px-[5px]" @click="show = false">
				<van-icon name="cross" size="25" />
			</div>
		</div>
		<van-address-list v-model="chosenAddressId" :list="addressList" default-tag-text="默认" @add="onAdd"
			add-button-text="选择其他地址" right-icon="" @select="changeAddress" />
	</van-popup>
	<van-popup v-model:show="payVisible" position="bottom"
		:style="{ height: '40%', overflow: 'auto', boxSizing: 'border-box' }">
		<div class="flex">
			<h2 class="text-[18px] text-center py-[15px] mx-[auto]">选择支付方式</h2>
			<div class="flex items-center px-[5px]" @click="payVisible = false">
				<van-icon name="cross" size="25" />
			</div>
		</div>
		<van-cell-group inset>
			<van-radio-group v-model="payType" shape="dot">
				<van-cell title="微信支付" value="内容" label="使用支付宝快捷支付">
					<template #value>
						<div class="flex items-center justify-end h-full" @click="showFailToast('暂未开通支付')">
							<van-radio :name="0" :disabled="true"></van-radio>
						</div>
					</template>
				</van-cell>
				<van-cell title="支付宝支付" value="内容" label="使用微信快捷支付">
					<template #value>
						<div class="flex items-center justify-end h-full">
							<van-radio :name="1"></van-radio>
						</div>
					</template>
				</van-cell>
			</van-radio-group>
		</van-cell-group>
		<div class="flex justify-center py-[10px] text-[20px]">
			<span class="text-[16px] mr-[5px] flex items-center">支付</span>
			<span class="text-[red]">¥{{ (totalPrice / 100).toFixed(2) }}</span>
		</div>
		<van-button type="danger" class="w-[90%] mx-auto" block @click="onSubmit">去付款</van-button>
	</van-popup>
	<van-dialog v-model:show="dialogVisible" theme="round-button"
		:confirmButtonText="orderInfo.state == 2 ? '完成' : '返回订单页面查看'" @confirm="payConfirm">
		<div class="h-[200px] flex justify-center items-center">
			<div v-if="orderInfo.state == 2" class="flex flex-col justify-center items-center">
				<van-icon color="green" size="80" name="checked" />
				<span class="text-[green] text-[20px] mt-[10px]">支付完成</span>
			</div>
			<van-loading size="70px" vertical text-color="#0094ff" color="#0094ff" v-else>
				<span class="text-[18px]">正在查询支付结果</span>
			</van-loading>
		</div>
	</van-dialog>
	>>>>>>> 27e61e513d5f3d08b03c3a597f91f6c63c10af44
</template>

<style scoped lang="scss">
.content {
	padding: 10px;
	height: calc(100vh - 130px);
	overflow: auto;
	background-color: #f6f6f6;
}

.van-card {
	background-color: #fff;
}

.van-cell {
	margin-top: 10px;
}
</style>
